package com.lqd.mall.jpa.service.impl;

import com.lqd.mall.basis.utils.ServletUtils;
import com.lqd.mall.basis.utils.reflect.ReflectUtils;
import com.lqd.mall.interaction.basis.vo.TableDataInfoVo;
import com.lqd.mall.jpa.constant.QueryConstants;
import com.lqd.mall.jpa.repository.BaseRepository;
import com.lqd.mall.jpa.service.BaseService;
import com.lqd.mall.jpa.utils.DynamicSqlUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;


/**
 * @author 零起点
 * @create 2022-03-11 10:42
 */
public class BaseServiceImpl<R extends BaseRepository<T, ID>, T, ID extends Serializable>
        implements BaseService<T, ID> {

    @Autowired
    R repository;


    @Override
    public Optional<Integer> delectEntity(T entity) {
        return repository.delectEntity(entity);
    }

    @Override
    public Optional<Integer>  updateEntity(T entity, String... attribute) {

        if (attribute.length == 0 || ObjectUtils.isEmpty(entity)) {
            return Optional.of(0);
        }
        return repository.updateEntity(entity, attribute);
    }

    @Override
    public TableDataInfoVo<T> list(T entity) {

        ReflectUtils.setFieldValue(entity,"delFlag","0");
        Integer pageNum = ServletUtils.getParameterToInt(QueryConstants.PAGE_NUM);
        Integer pageSize = ServletUtils.getParameterToInt(QueryConstants.PAGE_SIZE);
        if (pageNum != null && pageSize != null && pageNum > 0 && pageSize > 0) {
            Pageable pageable = PageRequest.of(pageNum - 1, pageSize);

            Page<T> repositoryAll = repository.findAll(DynamicSqlUtil.setQueryConditions(entity), pageable);
            TableDataInfoVo<T> infoVo = new TableDataInfoVo<>();
            infoVo.setTotal(repositoryAll.getTotalElements());
            List<T> content = repositoryAll.getContent();
            if (CollectionUtils.isEmpty(content)){
                content = new ArrayList<>();
            }
            infoVo.setRows(content);
            return infoVo;
        }
        List<T> all = repository.findAll(DynamicSqlUtil.setQueryConditions(entity));
        if (CollectionUtils.isEmpty(all)) {
            all = new ArrayList<>();
        }
        TableDataInfoVo<T> infoVo = new TableDataInfoVo<>();
        infoVo.setTotal(all.size());
        infoVo.setRows(all);
        return infoVo;

    }

    @Override
    public T selectById(ID dictId) {
        Optional<T> op = repository.findById(dictId);
        return op.orElse(null);
    }


}
